import axios from 'axios';
import Router from '@/router/index';
import {getToken, removeToken} from "@/libs/auth";
import tool from '@/libs/tool'

export const RESPONSE_CODE = {
    SUCCESS: '000',
    FAIL: '001',
};

// create an axios instance
const service = axios.create({
    baseURL: 'http://api-v2.local.dev', // api的base_url
    timeout: 20000 // request timeout
});

// request interceptor
// Do something before request is sent
service.interceptors.request.use(config => {

    // set header auth token
    let token = getToken();
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }

    // config.headers['Content-Type'] = 'application/x-www-form-urlencodeed';
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';

    return config
}, error => {

    return Promise.reject(error)
});


// respone interceptor
service.interceptors.response.use(
    response => {

        // check business code
        // if (response.data.meta.feedback !== undefined && response.data.meta.code !== '000') {
        //     tool.toast.show(viewId, 'server error');
        // }

        return response.data;
    },
    error => {

        // check login status
        if (error.response.status === 401) {
            removeToken();
            tool.toast.show('#app', 'login expired');
            setTimeout(() => {location.href = '/#/user/login';}, 3000);
            // setTimeout(() => {Router.push({name: 'login'});}, 3000);
        }

        return Promise.reject(error)
    }
);


export default service